
import React, { useEffect, useRef, useState } from 'react';
import './index.less';

interface Iprops {
  defaultValue: number;
  tipVisible?: boolean;
  change: (param: number) => void;
}
let thumbDarg = false; //是否可以拖拽
let thumbLeftStatic = 0;
let maxW = 0; //最大宽度

const UiSlider = (props: Iprops) => {
  const { tipVisible, defaultValue, change } = props;
  const refSilder = useRef<HTMLDivElement | null>(null); //滑动条
  const [left, setLeft] = useState(0);
  const [thumb, setThumb] = useState(thumbDarg); // 是否可以拖拽
  const [rate, setRate] = useState(defaultValue); // 是否可以拖拽

  // fn 拖拽
  function dargFn(e) {
    const refV = refSilder.current;
    if (thumbDarg && refV) {
      maxW = refV.clientWidth;
      thumbLeftStatic += e.movementX;
      thumbLeftStatic = thumbLeftStatic > maxW ? maxW : thumbLeftStatic;
      thumbLeftStatic = thumbLeftStatic < 0 ? 0 : thumbLeftStatic;
      const scale = thumbLeftStatic !== 0 ? Number(parseInt(`${(thumbLeftStatic / maxW) * 100}`, 10)) : 0;
      setLeft(thumbLeftStatic);
      setRate(scale);
    }
  }
  // fn 取消拖拽
  function cancelDargFn() {
    setThumb(false);
  }
  // fn 点击定位
  function inderCursurFn(e) {
    setThumb(true);
    const refV = refSilder.current;
    if (!e.target.className.includes('ui-slider-inner') && refV) {
      thumbLeftStatic = e.nativeEvent.layerX;
      const scale = Number(parseInt(`${(thumbLeftStatic / maxW) * 100}`, 10));
      setLeft(thumbLeftStatic);
      setRate(scale);
    }
  }
  // 初始化
  function initFn() {
    const refV = refSilder.current;
    if (refV && refV.clientWidth) {
      maxW = refV.clientWidth;
      thumbLeftStatic = Number(parseInt(`${maxW * (rate / 100)}`, 10));
      if (!isNaN(thumbLeftStatic)) setLeft(thumbLeftStatic);
    }
  }
  // 提示面板
  function renderTip() {
    if (tipVisible !== false) {
      return (
        <span style={{ display: `${thumb ? 'inline-block' : 'none'}` }} className="ui-slider-popup">
          {rate}
        </span>
      );
    } else {
      return '';
    }
  }
  useEffect(() => {
    thumbDarg = thumb;
  }, [thumb]);
  useEffect(() => {
    change(rate);
  }, [rate]);
  useEffect(() => {
    initFn();
  }, [refSilder.current?.clientWidth]);
  // 拖拽事件监听
  useEffect(() => {
    window.addEventListener('mousemove', dargFn);
    window.addEventListener('mouseup', cancelDargFn);
    return () => {
      window.removeEventListener('mousemove', dargFn);
      window.removeEventListener('mouseup', cancelDargFn);
      cancelDargFn();
    };
  }, []);
  return (
    <div ref={refSilder} className="ui-slider" onMouseDown={inderCursurFn.bind(this)}>
      <div style={{ width: `${rate}%` }} className="ui-slider-speed"></div>
      <span style={{ left: `${left}px` }} className="ui-slider-inner">
        {renderTip()}
      </span>
    </div>
  );
};

export default UiSlider;
